const express = require('express');
const router = express.Router();
const multer = require('multer');
const { User } = require('../models/db');

// ==================== 文件上传配置 ====================
const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 10 * 1024 * 1024 } // 10MB
});

// ==================== 控制器引入 ====================
const studentController = require('../controllers/studentController');
const teacherController = require('../controllers/teacherController');
const classController = require('../controllers/classController');
const attendanceController = require('../controllers/attendanceController');
const gradeController = require('../controllers/gradeController');
const dormitoryController = require('../controllers/dormitoryController');
const marketDepartmentController = require('../controllers/marketDepartmentController');
const roleController = require('../controllers/roleController');
const auditLogController = require('../controllers/auditLogController');

// ==================== 统一响应格式 ====================
const ok = (res, data, extra = {}) => res.json({ success: true, data, ...extra });
const fail = (res, code = 500, message = '服务器错误') => res.status(code).json({ success: false, message, code });

// ==================== 健康检查 ====================
router.get('/health', (req, res) => ok(res, { status: 'healthy', ts: new Date().toISOString() }));

// ==================== 认证相关 ====================
const crypto = require('crypto');
const jwtSecret = process.env.JWT_SECRET || 'sms-demo-secret';

function simpleJwt(user) {
  return crypto.createHash('md5').update(user._id + jwtSecret).digest('hex');
}

// 登录
router.post('/auth/login', async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) return fail(res, 400, '用户名/密码必填');
  
  const user = await User.findOne({ username });
  if (!user) return fail(res, 401, '用户不存在');
  if (user.password !== password) return fail(res, 401, '密码错误');
  
  const token = simpleJwt(user);
  
  // 记录登录日志
  await auditLogController.createLog(
    user._id.toString(),
    user.username,
    '登录',
    '系统登录',
    `用户 ${user.username} 登录系统`,
    req.ip || req.connection.remoteAddress,
    '成功'
  );
  
  ok(res, { token, user: { id: user._id, username: user.username, role: user.role } });
});

// 注册
router.post('/auth/register', async (req, res) => {
  const { username, password, role } = req.body;
  if (!username || !password) return fail(res, 400, '用户名/密码必填');
  
  let exist = await User.findOne({ username });
  if (exist) return fail(res, 400, '用户名已存在');
  
  const user = await User.create({ username, password, role: role || 'user' });
  ok(res, { id: user._id, username: user.username, role: user.role });
});

// ==================== 学生管理路由 ====================
router.get('/students', studentController.getAllStudents);
router.get('/students/:id', studentController.getStudentById);
router.post('/students', studentController.createStudent);
router.put('/students/:id', studentController.updateStudent);
router.delete('/students/:id', studentController.deleteStudent);
router.post('/students/:id/comments', studentController.addTeacherComment);

// ==================== 教师管理路由 ====================
router.get('/teachers', teacherController.getAllTeachers);
router.get('/teachers/:id', teacherController.getTeacherById);
router.post('/teachers', teacherController.createTeacher);
router.put('/teachers/:id', teacherController.updateTeacher);
router.delete('/teachers/:id', teacherController.deleteTeacher);

// ==================== 班级管理路由 ====================
router.get('/classes', classController.getAllClasses);
router.get('/classes/:id', classController.getClassById);
router.post('/classes', classController.createClass);
router.put('/classes/:id', classController.updateClass);
router.delete('/classes/:id', classController.deleteClass);

// ==================== 考勤管理路由 ====================
router.get('/attendances', attendanceController.getAllAttendances);
router.get('/attendances/:id', attendanceController.getAttendanceById);
router.post('/attendances', attendanceController.createAttendance);
router.put('/attendances/:id', attendanceController.updateAttendance);
router.delete('/attendances/:id', attendanceController.deleteAttendance);

// ==================== 成绩管理路由 ====================
router.get('/grades', gradeController.getAllGrades);
router.get('/grades/:id', gradeController.getGradeById);
router.post('/grades', gradeController.createGrade);
router.put('/grades/:id', gradeController.updateGrade);
router.delete('/grades/:id', gradeController.deleteGrade);
router.get('/grades/class/:classId/success-rate', gradeController.getClassSuccessRate);
router.get('/grades/export/template', gradeController.exportGradeTemplate);
router.post('/grades/import', upload.single('file'), gradeController.importGrades);
router.get('/grades/export', gradeController.exportGrades);

// ==================== 宿舍管理路由 ====================
router.get('/dormitories', dormitoryController.getAllDormitories);
router.get('/dormitories/:id', dormitoryController.getDormitoryById);
router.post('/dormitories', dormitoryController.createDormitory);
router.put('/dormitories/:id', dormitoryController.updateDormitory);
router.delete('/dormitories/:id', dormitoryController.deleteDormitory);
router.post('/dormitories/:id/students', dormitoryController.addStudentToDormitory);
router.delete('/dormitories/:id/students', dormitoryController.removeStudentFromDormitory);

// ==================== 市场部管理路由 ====================
router.get('/market-departments', marketDepartmentController.getAllMarketDepartments);
router.get('/market-departments/:id', marketDepartmentController.getMarketDepartmentById);
router.post('/market-departments', marketDepartmentController.createMarketDepartment);
router.put('/market-departments/:id', marketDepartmentController.updateMarketDepartment);
router.delete('/market-departments/:id', marketDepartmentController.deleteMarketDepartment);
router.post('/market-departments/:id/graduate-status', marketDepartmentController.updateGraduateStatus);

// ==================== 角色权限管理路由 ====================
router.get('/roles', roleController.getAllRoles);
router.get('/roles/:id', roleController.getRoleById);
router.post('/roles', roleController.createRole);
router.put('/roles/:id', roleController.updateRole);
router.delete('/roles/:id', roleController.deleteRole);

// ==================== 审计日志路由 ====================
router.get('/audit-logs', auditLogController.getAllAuditLogs);
router.get('/audit-logs/:id', auditLogController.getAuditLogById);
router.post('/audit-logs', auditLogController.createAuditLog);

module.exports = router;
